import { defineComponent, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { ElDialog, ElButton, ElForm, ElFormItem, ElInput, ElMessage } from 'element-plus'

import type { FormInstance, FormRules } from 'element-plus'
import { handleTrim } from '~/utils/util'
import type { InfoValuesType } from './typings'

export default defineComponent({
  props: ['cancel', 'type', 'visible', 'record'],
  setup(props) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const ruleForm = reactive<InfoValuesType>(
      Object.assign(
        {},
        props?.record?.id // 初始化数据
          ? {
              id: props.record.id,
              name: props.record.name,
              sort: props.record.sort
            }
          : {}
      )
    )

    const rules = reactive<FormRules>({
      name: [{ required: true, message: '分组名称不能为空', trigger: 'blur' }],
      sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
    })
    //  提交
    const submitForm = () => {
      ruleFormRef.value?.validate(async (valid) => {
        if (valid) {
          const params = { ...ruleForm }
          params.name = handleTrim(params.name!)
          if (props.type === 'update') params.id = props.record?.id
          const { code } = await store.dispatch(
            props.type === 'add' ? 'singleLamp/GroupAdd' : 'singleLamp/GroupUpdate',
            params
          )
          if (code === 200) {
            ElMessage({
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            props.cancel()
          }
        }
      })
    }
    //  取消
    const resetForm = () => {
      ruleFormRef.value?.resetFields()
      props.cancel()
    }
    return () => (
      <ElDialog
        title={props.type === 'add' ? '新增分组' : '编辑分组'}
        modelValue={props.visible}
        beforeClose={props.cancel}
        closeOnClickModal={false} // 点遮罩层不关弹窗
        draggable // 可拖拽
        width={500}
        v-slots={{
          footer: () => (
            <>
              <ElButton onClick={resetForm}>取消</ElButton>
              <ElButton type="primary" onClick={submitForm}>
                确定
              </ElButton>
            </>
          )
        }}
      >
        <ElForm
          ref={ruleFormRef}
          model={ruleForm}
          rules={rules}
          label-width="100px"
          inline={true}
          labelPosition="right"
        >
          <ElFormItem label="分组名称" prop="name">
            <ElInput v-model={ruleForm.name} placeholder="请输入分组名称"></ElInput>
          </ElFormItem>
          <ElFormItem label="排序" prop="sort">
            <ElInput v-model={ruleForm.sort} type="number" placeholder="请输入序号"></ElInput>
          </ElFormItem>
        </ElForm>
      </ElDialog>
    )
  }
})
